package com.business.business.web.service;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.business.business.common.base.BaseService;
import com.business.business.model.Business;
import com.business.business.model.Certificate;
import com.business.business.support.model.RespEntity;
import com.business.business.support.mybatisplus.QueryWrapper;
import com.business.business.support.utils.https.StringUtil;
import com.business.business.support.utils.requestutil.HttpRequestUtil;
import com.business.business.web.mapper.BusinessMapper;
import com.business.business.web.mapper.CertificateMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
* @author xulumin
* @description 针对表【certificate(证书表)】的数据库操作Service
* @createDate 2024-03-21 11:10:07
*/
@Service
public class CertificateService extends BaseService {

    @Resource
    private CertificateMapper certificateMapper;

    @Resource
    private BusinessMapper businessMapper;

    /**
     * Author: xulumin
     * Date: 2024/3/19
     * Description: 证书信息新增或更新
     */
    public RespEntity addOrUpdateCertificate(JSONObject jsonObject) {
        //处理支持form-data和json两种方式
        jsonObject = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonObject, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");

        // 获取bean
        Certificate certificate = jsonObject.toBean(Certificate.class);
        if (userType.equals("2")){
            certificate.setBusinessId(homeId);
        }
        // System.out.println(emgMaterials);

        // 判断必填字段
        if (StringUtil.strIsNullOrEmpty(certificate.getName()) || "null".equals(String.valueOf(certificate.getNumber()))) {
            return RespEntity.fail("请填写证书名称或者证书编号");
        }
        if (StringUtil.strIsNullOrEmpty(String.valueOf(certificate.getInitialDate())) || StringUtil.strIsNullOrEmpty(String.valueOf(certificate.getReviewDate()))) {
            return RespEntity.fail("请填写证书复审日期和证书到期日期");
        }
        if (StringUtil.strIsNullOrEmpty(certificate.getBusinessId()) || StringUtil.strIsNullOrEmpty(certificate.getBusinessName())) {
            return RespEntity.fail("请填写所属单位id和所属单位名称");
        }

        int result = -1;
        // 判断是否新增或更新
        if (StringUtil.strIsNullOrEmpty(certificate.getId())) {
            // 为空，新增
            certificate.setId(UUID.randomUUID().toString());
            result = certificateMapper.insert(certificate);
        } else {
            result = certificateMapper.updateById(certificate);
        }
        // 判断数据库是否操作成功
        if (result > 0) {
            return RespEntity.success();
        } else {
            return RespEntity.fail("操作失败！");
        }
    }

    /**
     * Author: xulumin
     * Date: 2024/3/19
     * Description: 获取证书信息列表
     */
    public RespEntity getCertificateList(JSONObject jsonObject) {
        //处理支持form-data和json两种方式
        jsonObject = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonObject, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");

        // 判断页码和页面大小
        Integer page = jsonObject.getInt("page");
        Integer limit = jsonObject.getInt("limit");

        page = "null".equals(String.valueOf(page)) ? 1 : page;
        limit = "null".equals(String.valueOf(limit)) ? 5 : limit;

        String areaId = jsonObject.getStr("areaId");
        String businessId = jsonObject.getStr("businessId");
        Page<Certificate> pageInfo = new Page<>(page, limit);
        if (StringUtil.strIsNullOrEmpty(areaId) && !StringUtil.strIsNullOrEmpty(businessId)) {
            // 区域Id为空，按企业查
            // 构建查询条件
            LambdaQueryWrapper<Certificate> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.like(jsonObject.containsKey("name"), Certificate::getName, jsonObject.getStr("name"))
                    // 按单位
                    .eq(jsonObject.containsKey("businessId"), Certificate::getBusinessId, jsonObject.getStr("businessId"));
            IPage<Certificate> iPage = certificateMapper.selectPage(pageInfo, lambdaQueryWrapper);
            return RespEntity.success(iPage);
        } else if (StringUtil.strIsNullOrEmpty(businessId) && !StringUtil.strIsNullOrEmpty(areaId)) {
            // 企业Id为空，按照区域查
            // 查询该区域下企业
            LambdaQueryWrapper<Business> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.like(Business::getArea, areaId).select(Business::getId);
            List<Business> businesses = businessMapper.selectList(lambdaQueryWrapper);
            List<String> ids = new ArrayList<>();
            for (Business business : businesses) {
                ids.add(business.getId());
            }
            // 构建查询条件
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.in("business_id", ids);
            // 开始查询全部证书
            int certificateNumber = certificateMapper.selectCount(queryWrapper);
            //  查询过期证书
            Date currentDate = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 指定日期格式
            String Date = sdf.format(currentDate);
            System.out.println("Current date: " + Date);
            queryWrapper.lt("due_date", Date);
            int certificateDue = certificateMapper.selectCount(queryWrapper);
            // 有效证书
            int certificateValid = certificateNumber -certificateDue;

            Map<String, Object> map = new HashMap<>();
            map.put("certificateNumber", certificateNumber);
            map.put("certificateDue", certificateDue);
            map.put("certificateValid", certificateValid);

            return RespEntity.success(map);
        } else {
            // 企业ID和区域ID都为空
            LambdaQueryWrapper<Certificate> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.like(jsonObject.containsKey("name"), Certificate::getName, jsonObject.getStr("name"))
                    // 按单位
                    .eq(jsonObject.containsKey("businessId"), Certificate::getBusinessId, jsonObject.getStr("businessId"));
            IPage<Certificate> iPage = certificateMapper.selectPage(pageInfo, lambdaQueryWrapper);
            return RespEntity.success(iPage);
        }
    }


    /**
     * Author: xulumin
     * Date: 2024/3/19
     * Description: 获取区域下证书信息列表
     */
    public RespEntity getCertificateAreaList(JSONObject jsonObject) {
        //处理支持form-data和json两种方式
        jsonObject = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonObject, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");


        String areaId = jsonObject.getStr("areaId");
        if (!StringUtil.strIsNullOrEmpty(areaId)) {
            LambdaQueryWrapper<Business> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.like(Business::getArea, areaId).select(Business::getId);
            List<Business> businesses = businessMapper.selectList(lambdaQueryWrapper);
            List<String> ids = new ArrayList<>();
            for (Business business : businesses) {
                ids.add(business.getId());
            }
//            System.out.println(businesses);

            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.in("business_id", ids);
            // 开始查询全部证书
            int certificateNumber = certificateMapper.selectCount(queryWrapper);
            //  查询过期证书
            Date currentDate = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 指定日期格式
            String Date = sdf.format(currentDate);
//            System.out.println("Current date: " + Date);
            queryWrapper.lt("due_date", Date);
            int certificateDue = certificateMapper.selectCount(queryWrapper);
            // 有效证书
            int certificateValid = certificateNumber -certificateDue;

            Map<String, Object> map = new HashMap<>();
            map.put("全部证书", certificateNumber);
            map.put("过期证书", certificateDue);
            map.put("有效证书", certificateValid);

            return RespEntity.success(map);
        }

        // 判断页码和页面大小
        Integer page = jsonObject.getInt("page");
        Integer limit = jsonObject.getInt("limit");

        page = "null".equals(String.valueOf(page)) ? 1 : page;
        limit = "null".equals(String.valueOf(limit)) ? 5 : limit;

        // 构建查询条件
        Page<Certificate> pageInfo = new Page<>(page, limit);
        LambdaQueryWrapper<Certificate> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(jsonObject.containsKey("name"), Certificate::getName, jsonObject.getStr("name"))
                // 按单位
                .eq(jsonObject.containsKey("businessId"), Certificate::getBusinessId, jsonObject.getStr("businessId"));
        IPage<Certificate> iPage = certificateMapper.selectPage(pageInfo, lambdaQueryWrapper);
        return RespEntity.success(iPage);
    }


    /**
     * Author: xulumin
     * Date: 2024/3/19
     * Description: 证书删除
     */
    public RespEntity delCertificate(JSONObject jsonObject) {
        //处理支持form-data和json两种方式
        jsonObject = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonObject, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");

        // 获取要删除的物资id
        String ids = jsonObject.getStr("id");
        String[] split = ids.split(",");
        int result = certificateMapper.deleteBatchIds(Arrays.asList(split));
        if (result == split.length) {
            return RespEntity.success("删除成功");
        } else {
            return RespEntity.fail("删除失败");
        }
    }

    /**
     * Author: xulumin
     * Date: 2024/3/20
     * Description: 获取证书信息
     */
    public RespEntity getCertificateInfo(JSONObject jsonObject) {
        //处理支持form-data和json两种方式
        jsonObject = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonObject, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");

        // 获取物资id
        String id = jsonObject.getStr("id");
        if (StringUtil.strIsNullOrEmpty(id)) {
            return RespEntity.fail("请填写要查询的id");
        }
        Certificate certificate = certificateMapper.selectById(id);
        if (certificate != null) {
            return RespEntity.success(certificate);
        } else {
            return RespEntity.fail("查询失败");
        }

    }


}
